package com.springsummer.information.green.webmvc;

import com.springsummer.information.green.beans.ApplicationContext;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

public class RequestMappingHandlerMapping implements HandlerMapping{

    private static Logger logger=Logger.getLogger(RequestMappingHandlerMapping.class.getName());

    protected NormalHandlerMappingRegistry mappingRegistry;

    protected ApplicationContext applicationContext;

    public RequestMappingHandlerMapping() {
        this.mappingRegistry=new NormalHandlerMappingRegistry();
    }

    public RequestMappingHandlerMapping(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        this.mappingRegistry=new NormalHandlerMappingRegistry(applicationContext);
    }

    public void initMapping(String[] controllerNames) throws Exception {
        if(null!=controllerNames){
            for(String cname:controllerNames){
                logger.info("RequestMappingHandlerMapping initMapping name:"+cname);
            }
        }
        mappingRegistry.initMapping(controllerNames);
    }

    @Override
    public HandlerMethodInfo getHandler(HttpServletRequest request) throws Exception {
        String urlRaw=request.getRequestURL().toString();
        String useUrl=urlRaw;
        if(urlRaw.contains("http")){
            //String sPath = request.getServletPath();
            useUrl=request.getServletPath();
        }
        boolean containsed= mappingRegistry.containsHandler(useUrl);
        HandlerMethodInfo handlerMethod=null;
        if(containsed){
            handlerMethod= findHandlerMethod(useUrl);
        }
        logger.info("RequestMappingHandlerMapping getHandler url:"+useUrl+" HandlerMethod:"+handlerMethod);
        return handlerMethod;
    }


    public HandlerMethodInfo findHandlerMethod(String url) {
        return mappingRegistry.findHandlerMethod(url);
    }

}
